<!doctype html>
<html lang="zh">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>RustU</title>
        <link rel="stylesheet" href="styles.css" />
        <link
            rel="stylesheet"
            type="text/css"
            href="/assets/css/bootstrap.min.css"
        />
        <script
            type="text/javascript"
            src="/assets/js/bootstrap.bundle.min.js"
        ></script>
        <script
            type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.js"
        ></script>
        <script>
            function validateAndPreview(event) {
                console.log(event.target.files[0].name);
                let file = event.target.files[0];
                if (file) {
                    const fileName = file.name;
                    const fileExtension = fileName.split(".");
                    if (fileExtension.length > 1) {
                        if ("md" !== fileExtension[fileExtension.length - 1]) {
                            showModel(
                                "错误",
                                "文件格式不正确，请选择Markdown文件！",
                            );
                            //设置按钮不可点击
                            changeButtonStatus(false);
                            return;
                        } else {
                            changeButtonStatus(true);
                            //预览文件
                            previewFile(file);
                        }
                    } else {
                        showModel(
                            "校验失败",
                            "文件格式不正确，请选择Markdown文件！",
                        );
                        return;
                    }
                } else {
                    showModel(
                        "校验失败",
                        "文件格式不正确，请选择Markdown文件！",
                    );
                    return;
                }
            }

            function previewFile(file) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const preview = document.getElementById("preview");
                    const content = e.target.result;
                    const html_content = marked.parse(content);
                    preview.innerHTML = html_content;
                };
                reader.readAsText(file);
            }

            function showModel(title, content) {
                document.getElementById("modelTitle").textContent = title;
                document.getElementById("modelContent").innerHTML = content;
                const alertModel = new bootstrap.Modal("#alertModel", {
                    focus: true,
                });
                alertModel.show();
            }

            function changeButtonStatus(status) {
                const uploadBtn = document.getElementById("uploadBtn");
                if (status) {
                    uploadBtn.disabled = !status;
                    uploadBtn.classList.remove("disabled");
                } else {
                    uploadBtn.disabled = !status;
                    uploadBtn.classList.add("disabled");
                }
            }

            function upload() {
                const fileInput = document.getElementById("uploadFile");

                if (!fileInput.files || !fileInput.files[0]) {
                    alert("请先选择一个文件");
                    return;
                }

                const file = fileInput.files[0];
                const formData = new FormData();
                formData.append("file", file);

                fetch("/blog/new", {
                    method: "POST",
                    body: formData,
                })
                    .then((response) => {
                        if (!response.ok) {
                            throw new Error(
                                `服务器返回错误：${response.status} ${response.statusText}`,
                            );
                        }
                        return response.text(); // 重点：使用 text() 解析文本响应
                    })
                    .then((text) => {
                        console.log("上传成功，服务器返回：", text);
                        showModel("上传成功", text); // 假设 showModel 是你自定义的弹窗函数
                    })
                    .catch((error) => {
                        console.error("上传失败:", error);
                        showModel("上传失败", "原因：" + error.message);
                    });
            }
        </script>
    </head>
    <body class="mt-5">
        <div class="container content-wrap">
            <div class="row">
                <div class="col-4">
                    <label for="formFile" class="form-label"
                        >请选择要上传的markdown文件</label
                    >
                    <input
                        class="form-control"
                        type="file"
                        name="file"
                        id="uploadFile"
                        onchange="validateAndPreview(event)"
                    />

                    <button
                        onclick="upload()"
                        id="uploadBtn"
                        class="btn btn-primary mt-2 disabled"
                        disabled
                    >
                        上传
                    </button>

                    <!-- Modal -->
                    <div
                        class="modal fade"
                        id="alertModel"
                        tabindex="-1"
                        aria-labelledby="exampleModalLabel"
                        aria-hidden="true"
                    >
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h1
                                        class="modal-title fs-5"
                                        id="modelTitle"
                                    >
                                        Modal title
                                    </h1>
                                    <button
                                        type="button"
                                        class="btn-close"
                                        data-bs-dismiss="modal"
                                        aria-label="Close"
                                    ></button>
                                </div>
                                <div class="modal-body" id="modelContent">
                                    ...
                                </div>
                                <div class="modal-footer">
                                    <button
                                        type="button"
                                        class="btn btn-secondary"
                                        data-bs-dismiss="modal"
                                    >
                                        Close
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-8">
                    <h3>预览</h3>
                    <pre id="preview" aria-placeholder="预览"></pre>
                </div>
            </div>
        </div>
    </body>
</html>
